<?php
namespace app\api\controller;
/**
 * User: huangzhen
 * Date: 2025/05/23
 */

use app\common\model\ManageLog;
use think\facade\Db;
use app\common\model\Cards as cardsModel;
use app\common\model\User as userModel;
use think\facade\Request;
use think\facade\Cache;

class TimerUsdt
{

    public function __construct()
    {
        $params = Request::param();
        if (empty($params)) {
            exit('Welcome to cardecho');
        } else {
            $token = $params['token'];
            //234b4e50a80527e1e1a394a030f8687d
            if ($token != md5(md5('vvacard') . md5(202505))) {
                exit('Welcome to vvacard !');
            }
        }
    }

    public function index()
    {
        exit('Welcome to vvacard 2025 !');
    }

    public function getUsdtLog()
    {
        $user_key       =   getSetting('oy_fund_user');
        $USDT_CONTRACT  =   "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";
        $API_URL        =   "https://api.trongrid.io/v1/accounts";
        $limit          =   50;
        $header         = [
            'Content-Type: application/json'
        ];

        $url = $API_URL . "/{$user_key}/transactions/trc20?limit={$limit}&only_to=true&contract_address={$USDT_CONTRACT}";

        $curl_array = [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_USERAGENT => "Mozilla/5.0 (Tronscan PHP Listener)",
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_SSL_VERIFYPEER=>false //不检查 ssl
        ];
        $curl = curl_init();
        curl_setopt_array($curl, $curl_array);
        $response = curl_exec($curl);
        $list = [];
        if (curl_errno($curl)) {
            $list[] = [
                'transaction_id' => curl_error($curl)
            ];
        }else{
            if(!empty($response)){
                $data = json_decode($response, true);

                $transfers = isset($data["data"]) ? $data["data"] : [];
                if (!empty($transfers)) {
                    foreach ($transfers as $tx) {
                        $txid = $tx["transaction_id"];
                        $from = $tx["from"] ?? "";
                        $to = $tx["to"] ?? "";
                        $amount = floatval($tx["value"]) / 1e6;
                        $ts = intval($tx["block_timestamp"]) / 1000;
                        $time_str = date("Y-m-d H:i:s", $ts);
                        $check_txid = Db::name('api_accept_oy')->where(['txid'=>$txid])->find();
                        $type = $tx["type"] ?? "";
                        $adress = $tx['token_info']["address"] ?? "";
                        if(empty($check_txid)){
                            Db::name('api_accept_oy')->save([
                                "txid" => $txid,
                                "ctime" => $time_str,
                                "amount" => $amount,
                                "from" => $from,
                                "to" => $to,
                                "type" => $type,
                                "is_action" => ($type == 'Approval')?2:0,
                                "address" => $adress,
                                "detail"   =>json_encode($tx),
                            ]);
                        }
                    }
                }
            }
        }
        curl_close($curl);
        self::actionOyfund();
    }

    public static function actionOyfund()
    {
        $list     = Db::name('fund_check_oy')
            ->where("status_check=0")
            ->select()->toArray();
        $utime    = getUtcTime(false);
        $time     = strtotime($utime);
        //本地时间比USDT服务器时间少13小时,那么把超过24小时的爬虫记录更新为-已过期
        $del_time  = $time - 11 * 60 * 60;
        $del_time  = date('Y-m-d H:i:s',$del_time);
        Db::name('api_accept_oy')
            ->where("ctime < '{$del_time}' and is_action=0")
            ->update(['is_action' =>3]); //1=已处理 0=默认未处理 2=AppL已处理 3=已过期

        //用户24小内充值总金额没有超过N时就正常入帐，否则就等管理员审核后手动入帐
        $usdt_fund_limit  =  getSetting('usdt_fund_limit');
        $hy_address       =  "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";
        $oy_fund_user       = getSetting('oy_fund_user');
        $exp_fund_time    =  $time - 24 * 60 * 60;

        if(!empty($list)){
            foreach ($list as $k=>$v){
                $id     = $v['id'];
                $user_id= $v['user_id'];
                $amount = $v['amount'];//需要增加到用户余额
                $amount_real = $v['amount_real'];//需要和爬虫日志金额对比的
                $old_time = strtotime($v['ctime']);
                $out_trade_no = $v['out_trade_no'];

                //用户24小内充值总金额没有超过N时就正常入帐，否则就等管理员审核后手动入帐
                $exp_fund_total = Db::name('fund_check_oy')
                    ->field("sum(amount) as total_amount")
                    ->where("UNIX_TIMESTAMP(ctime) > {$exp_fund_time} and status_used=1 and user_id={$user_id}")
                    ->find();
                $exp_fund_total_amount = $exp_fund_total['total_amount'] ?? 0;

                if($exp_fund_total_amount - $usdt_fund_limit > 0){
                    Db::name('fund_check_oy')
                        ->where(['id'=>$id])
                        ->update([
                            'status_check'    => 6,  //6=超额等处理
                        ]);
                }
                else{
                    //如果订单超过30分钟视为过期
                    if($time - $old_time > 30*60){
                        //0=未处理 1=已处理 2=处理失败 3=已过期 4=取消充值 5=工单处理 6=超额等处理
                        Db::name('fund_check_oy')
                            ->where(['id'=>$id])
                            ->update([
                                'status_check'    => 3,  //3=已过期
                                'utime'           => $utime,
                            ]);
                    }
                    else{
                        //判断爬虫日志中是否有匹配的金额
                        $check_api_list = Db::name('api_accept_oy')
                            ->where("amount = {$amount_real} 
                            and is_action = 0 
                            and type = 'Transfer'
                            and address = '{$hy_address}'
                            and `to` = '{$oy_fund_user}' ")->find();
                        $blog = false;
                        if(!empty($check_api_list)){
                            $oy_accept_id   = $check_api_list['id'];
                            $hash           = $check_api_list['txid'];
                            $real_amount    = intval($amount);
                            Db::startTrans();
                            try {
                                $user_list      = Db::name('user')->find($user_id);
                                $user_balance   = $user_list['balance'];
                                $username       = $user_list['username'];
                                $result_balance = $user_balance + $real_amount;
                                //记录钱包日志
                                Db::name('user_cash_log')->save([
                                    'user_id'       => $user_id,
                                    'type'          => 0, //1=debit
                                    'action_type'   => 1, //3=消费
                                    'amount'        => $real_amount,
                                    'balance'       => $result_balance, //如果是进行修复的话，这里的余额要重新计算
                                    'desc'          => "USDT充值",
                                    'remark'        => $out_trade_no,
                                    'ctime'         => $time
                                ]);
                                //记录到总充值列表中
                                $check_num  = 'U' . getRandNumber();
                                Db::name('fund_check')->save([
                                    'user_id'       => $user_id,
                                    'check_num'     => $check_num,
                                    'amount'        => $amount,
                                    'balance'       => $result_balance,
                                    'ctime'         => $time,
                                    'utime'         => $time,
                                    'check_status'  => 1,
                                    'pay_type'      => 6,  //6=usdt付款
                                    'trn'           => $out_trade_no,
                                    'desc'          => "USDT充值",
                                    'hash'          => $hash
                                ]);
                                //更新usdt充值列表
                                Db::name('fund_check_oy')
                                    ->where(['id'=>$id])
                                    ->update([
                                        'status_check'    => 1,
                                        'status_used'     => 1,
                                        'utime'           => $utime,
                                    ]);
                                //充值成功后更新用户余额
                                Db::name('user')->where(['id'=>$user_id])->update(['balance'=>$result_balance]);
                                //成功后更新usdt抓取日志
                                Db::name('api_accept_oy')
                                    ->where(['id'=>$oy_accept_id])
                                    ->update([
                                        'is_action' => 1, //1=已处理 0=默认未处理
                                        'out_trade_no' => $out_trade_no,
                                        'user_id'   => $user_id,
                                        'utime'     => $utime
                                    ]);
                                $blog = true;
                                Db::commit();
                            } catch (\Exception $e) {
                                $error_msg  = $e->getMessage();
                                Db::name('fund_check_oy')
                                    ->where(['id'=>$id])
                                    ->update([
                                        'status_check'    => 2, //处理失败
                                        'utime'           => $utime,
                                    ]);
                                Db::name('error_oy')->save([
                                    'user_id'       => $user_id,
                                    'error_msg'     => $error_msg,
                                    'detail'        => json_encode([
                                        'out_trade_no' => $out_trade_no
                                    ]),
                                    'time'          => $utime
                                ]);
                                var_dump($error_msg . $e->getLine());
                                Db::rollback();
                            }
                            if($blog){
                                EmailSend::sendGridEmail('usdt_fund_amount' , [
                                    'email'     => "sensir267@gmail.com",
                                    'body'      => "管理员您好，账号:{$username}<br />
                                        usdt已充值,$ {$real_amount} , 实际充值 $ {$amount_real}<br />
                                       cardecho运营小组<br />",
                                    'title'     => "账号({$username}-USDT充值-{$real_amount}) -- CardEcho",
                                ]);
                                EmailSend::sendGridEmail('usdt_fund_amount' , [
                                    'email'     => "897194@gmail.com",
                                    'body'      => "管理员您好，账号:{$username}<br />
                                        usdt已充值,$ {$real_amount} , 实际充值 $ {$amount_real}<br />
                                       cardecho运营小组<br />",
                                    'title'     => "账号({$username}-USDT充值-{$real_amount}) -- CardEcho",
                                ]);

                            }
                        }
                    }
                }
            }
        }
    }
}